package com.cmf.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cmf.common.PageResult;
import com.cmf.common.Result;
import com.cmf.dto.EmployeeDto;
import com.cmf.dto.EmployeeLoginDto;
import com.cmf.dto.EmployeeUpdateDto;
import com.cmf.entity.Employee;
import com.cmf.enums.EmployeeStatus;
import com.cmf.enums.Gender;
import com.cmf.enums.ResultCodeType;
import com.cmf.exception.BusinessException;
import com.cmf.mapper.EmployeeMapper;
import com.cmf.service.EmployeeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cmf.vo.EmployeeVo;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: cmf
 * @Date: 2025/8/27 16:16
 * @Version: v1.0.0
 * @Description: 员工服务实现类
 **/
@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements EmployeeService {
    @Override
    public Result<EmployeeVo> login(HttpServletRequest httpServletRequest, EmployeeLoginDto employeeLoginDto) {
       
    
        // 2、密码md5加密
        String password = SecureUtil.md5(employeeLoginDto.getPassword());
        
        // 3、查询数据库
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername, employeeLoginDto.getUsername());
        Employee employee = this.getOne(queryWrapper);
        
        // 4、判断账号是否存在
        if (employee == null) {
            // return Result.error(ResultCodeType.USER_NOT_EXIST, "账号不存在");
            throw new BusinessException(ResultCodeType.USER_NOT_EXIST,"账号不存在");
        }
        
        // 5、密码比对
        if (!employee.getPassword().equals(password)) {
            // return Result.error(ResultCodeType.UNAUTHORIZED, "密码错误");
            throw new BusinessException(ResultCodeType.UNAUTHORIZED,"密码错误");
        }
        
        // 6、判断账号是否可用
        if (employee.getStatus() == EmployeeStatus.DISABLED) {
            // return Result.error(ResultCodeType.USER_ACCOUNT_LOCKED, "账号已被禁用");
            throw new BusinessException(ResultCodeType.USER_ACCOUNT_LOCKED,"账号已被禁用");
        }

        EmployeeVo employeeVo =  EmployeeVo.builder()
                .id(employee.getId())
                .name(employee.getName())
                .phone(employee.getPhone())
                .idNumber(employee.getIdNumber())
                .sex(employee.getSex())
                .status(employee.getStatus())
                .username(employee.getUsername()).build();

        httpServletRequest.getSession().setAttribute("employee", employeeVo.getId());
        // 7、登录成功
        return Result.ok(employeeVo);
    }

    @Override
    public Result<Void> logout(HttpServletRequest httpServletRequest) {
        httpServletRequest.getSession().removeAttribute("employee");
        return Result.ok();
    }

    @Override

    public Result<Void> addEmployee(EmployeeDto employeeDto) {


            Employee employee = Employee.builder()
                .username(employeeDto.getUsername())
                .name(employeeDto.getName())
                .phone(employeeDto.getPhone())
                .sex(Gender.getGenderByGender(employeeDto.getSex()))
                .idNumber(employeeDto.getIdNumber())
                .status(EmployeeStatus.ENABLED)
                .password(SecureUtil.md5("123456"))
                .build();
            this.save(employee);
            return Result.ok();

    }

    @Override
    public Result<PageResult<EmployeeVo>> findPage(Long page, Long pageSize, String name) {
        Page<Employee> pageInfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<Employee> employeeLambdaQueryWrapper = new LambdaQueryWrapper<>();
        employeeLambdaQueryWrapper
                .like(name != null, Employee::getName, name)
                .orderByDesc(Employee::getCreateTime);
        Page<Employee> employeePage = this.baseMapper.selectPage(pageInfo, employeeLambdaQueryWrapper);
        List<Employee> records = employeePage.getRecords();
//        List<EmployeeVo> employeeVoList = records.stream().map(item -> {
//            return BeanUtil.copyProperties(item, EmployeeVo.class);
//        }).collect(Collectors.toList());
        List<EmployeeVo> employeeVoList = BeanUtil.copyToList(records, EmployeeVo.class);

        PageResult<EmployeeVo> pageResult = new PageResult<>(employeePage.getTotal(), employeeVoList);
        return Result.ok(pageResult);
    }

    @Override
    public Result<EmployeeVo> findById(Long id) {
        Employee employee = this.getById(id);
        if (employee != null) {
            return Result.ok(BeanUtil.copyProperties(employee, EmployeeVo.class));
        }
        return Result.error(ResultCodeType.USER_NOT_EXIST);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> updateEmployee(EmployeeUpdateDto employeeDto) {
        Employee hasEmployee = this.getById(employeeDto.getId());
        if (hasEmployee == null) {
            throw  new BusinessException(ResultCodeType.USER_NOT_EXIST);
        }
        Employee employee = BeanUtil.copyProperties(employeeDto, Employee.class);
        this.updateById(employee);
        return Result.ok();
    }
}
